package com.ybg.shareadmin.web;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.ybg.framework.core.RedisClient;
import com.ybg.framework.core.SecurityUser;
import com.ybg.framework.core.SecurityUtils;
import com.ybg.framework.vo.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.LinkedHashMap;
import java.util.Map;
@Api(description = "登录接口")
@Slf4j
@RestController

public class LoginController {

    @Value("${oauth2.baseAuthUrl}")
    private String oauthBaseUrl;
    @Value("${oauth2.clientId}")
    private String oauthClientId;

    @Value("${oauth2.appSecret}")
    private String oauthSecret;
    @Autowired
    private TokenStore redisTokenStore;


//127.0.0.1:8090/ybg_share/loginIn?username=admin&password=123456
    @ApiOperation(value = "登入")
    @PostMapping("loginIn")
    public R login(HttpServletRequest request,
                   @ApiParam(name = "username", value = "账号", required = true) @RequestParam("username") String username,
                   @ApiParam(name = "password", value = "密码", required = true) @RequestParam("password") String password,
                   @ApiParam(name = "code", value = "验证码", required = false) @RequestParam(value="code",required = false) String code) {
        log.info("登入");
        Map<String, Object> resultMap = new LinkedHashMap<>(4);
        Map<String, Object> formMap = new LinkedHashMap<>(5);
        if (username != null && username.trim().length() > 0) {
            formMap.put("username", username);
            formMap.put("password", password);
            formMap.put("grant_type", "password");
            // spingboot2.0 不能穿头部验证了 传入clientId和密钥
            formMap.put("client_id", oauthClientId);
            formMap.put("client_secret", oauthSecret);
            log.info(oauthBaseUrl + "/oauth/token");
            String result = HttpRequest.post(oauthBaseUrl + "/oauth/token").form(formMap)
                    // .basicAuth(oauthClientId, oauthSecret) springboot2.0 不能这么传
                    .execute().body();
            log.info(result);
            JSONObject json = JSONObject.parseObject(result);
            try {
                resultMap.put("access_token", json.get("access_token").toString());
                resultMap.put("refresh_token", json.get("refresh_token").toString());
                resultMap.put("expires_in", json.get("expires_in").toString());
                resultMap.put("userName",username);
                resultMap.put("roles",new String[]{"shareadmin"});
                //resultMap.put("user", redisTokenStore.readAuthentication(json.get("access_token").toString()));
                return R.success(resultMap);
            } catch (Exception e) {
                e.printStackTrace();
                if (json.get("error_description") != null
                        && json.get("error_description").toString().trim().length() > 0) {
                    return R.fail(json.get("error_description").toString());
                }

                return R.fail("账号密码错误");
            }

        }

        return R.fail("账号密码错误");

    }
    @PreAuthorize("isAuthenticated()")
    @ApiOperation(value = "登出")
    @GetMapping("loginOut")
    public R loginOut(HttpServletRequest request,
                           @ApiParam(name = "access_token", value = "用户凭证", required = true) @RequestParam("access_token") String token) {
        if (token != null) {
            OAuth2AccessToken accessToken = redisTokenStore.readAccessToken(token);
            redisTokenStore.removeAccessToken(accessToken);
        } else {
            return R.fail("非法token");
        }
        return R.success();

    }
    @PreAuthorize("isAuthenticated()")
    @PostMapping("getUserInfo")
    public R<SecurityUser> getUserInfo(){

        SecurityUser user=  (SecurityUser) SecurityUtils.getAuthentication().getPrincipal();

        return R.success(user);
    }


}
